package org.acsis.jee.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.acsis.jee.util.ClassLoaderUtil;
import org.apache.log4j.Logger;

public class Email {

	private static final Logger log = Logger.getLogger(Email.class);
	private static Properties props;
	
	private static final String senderProp = "mail.default.sender";
	private static final String senderpswProp = "mail.default.psw";
	
	private static String sender;
	private static String senderpsw;
	
	static {
		
		props = ClassLoaderUtil.loadProperties("mail");
		
		sender = props.getProperty(senderProp);
		senderpsw = props.getProperty(senderpswProp);
	}
	
	public static boolean sendMail(String to, String subject, String text)
	{

    	Session session = Session.getDefaultInstance(props,	new EMailAuthenticator(sender, senderpsw));		
    		 
    	try {
 
	        Message message = new MimeMessage(session);
		    message.setFrom(new InternetAddress(sender));
		    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		    message.setSubject(subject);
		    message.setText(text);
	 
		    Transport.send(message);
		    
		    log.info("mail sended");
		    
    	} catch (MessagingException e) {
    	    e.printStackTrace();
    		return false;
    	}
		
    	return true;
	}
	
	public static Properties getProperties(){
		return props;
	}
}
